package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.UserLocation;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


@Service
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Double longitude, Double latitude, UserLocation userLocation) {
        long timeMillis = System.currentTimeMillis();
        Query query = new Query(Criteria.where("userId").is(userLocation.getUserId()));
        GeoJsonPoint location = new GeoJsonPoint(longitude, latitude);
        if (mongoTemplate.exists(query, UserLocation.class)){
            Update update = new Update();
            update.set("location",location);
            update.set("created",timeMillis);
            update.set("address",userLocation.getAddress());
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }else {
            userLocation.setLocation(location);
            userLocation.setCreated(timeMillis);
            userLocation.setUpdated(timeMillis);
            mongoTemplate.insert(userLocation);
        }


    }
}
